import authorize from '@/utils/authorize/index.js'

/**
 * @desc 获取位置
 * @returns {Promise<Object>}
 */
function getLocation() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			isHighAccuracy: true,
			success: (res) => {
				resolve({ code: 200, data: res })
			},
			fail: () => {
				resolve({ code: 210, err: '获取定位失败' })
			}
		})
	})
}

/**
 * @desc 选择位置
 * @param storeName {String} 店铺名称
 * @returns {Promise<Object>}
 */
function chooseAddress(storeName) {
	return new Promise(async (resolve, reject) => {
		const res = await authorize('scope.userLocation');
		if (res['code'] !== 200) {
			return resolve({ code: 210, err: res['err'] })
		}

		const response = await getLocation();
		if (response['code'] !== 200) {
			return resolve({ code: 210, err: response['err'] })
		}

		let latitude = '';
		let longitude = '';
		if (response['code'] === 200) {
			latitude = response['data']['latitude']
			longitude = response['data']['longitude']
		}

		uni.chooseLocation({
			latitude,
			longitude,
			keyword: storeName,
			success: (res) => {
				resolve({ code: 200, data: res })
			},
			fail: (err) => {
				resolve({ code: 210, err })
			}
		})
	})
}

export default chooseAddress;